//编译模块
#pragma once
#include<iostream>
#include <sys/types.h>
#include <unistd.h>
#include"../comm/util.hpp"
#include <sys/wait.h>
#include <fcntl.h>
#include <sys/stat.h>
#include"../comm/log.hpp"
#include<errno.h>
#include<string.h>

namespace ns_compiler
{
  
    using namespace ns_util;
    using namespace ns_log;

    class Compiler
    {
    public:
        Compiler()
        {}
        ~Compiler()
        {}
       
        static bool Compile(const std::string &file_name)
        {
            pid_t pid = fork();
            if(pid < 0)
            {
                LOG(ERROR) << "内部错误，创建子进程失败" << "\n";
               
                return false;
            }
            else if (pid == 0)
            {
                umask(0);
                int _stderr = open(PathUtil::CompilerError(file_name).c_str(), O_CREAT | O_WRONLY, 0644);
                if(_stderr < 0){
                    LOG(WARNING) << "没有成功形成stderr文件" << "\n";
                    exit(1);
                }
                 
                //重定向标准错误
                dup2(_stderr, 2);
                execlp("g++", "g++", "-o", PathUtil::Exe(file_name).c_str(),\
                PathUtil::Src(file_name).c_str(),"-std=c++11","-D","CompileOnline", nullptr);
                LOG(ERROR) << "编译器g++失败，检查参数" << "\n";
                exit(2);
            }
            else{
                waitpid(pid, nullptr, 0);
              
                if(FileUtil::IsFileExists(PathUtil::Exe(file_name))){
                    LOG(INFO) << PathUtil::Src(file_name) << " 编译成功!" << "\n";
                    return true;
                }
            }
            LOG(ERROR) << "编译失败，没有形成可执行程序" << "\n";
            return false;
        }
    };

  





}